package com.foxzzz.datamemory.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foxzzz.datamemory.entity.ReadRecord;
import com.foxzzz.datamemory.util.HttpSendUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Service
public class DocService {
    private final static Logger logger = LoggerFactory.getLogger(DocService.class);
    @Value("${server.port:8080}")
    private Integer port;
    @Value("${ssh.port:22}")
    private Integer sshPort;
    @Value("${ssh.host}")
    private String sshHost;
    @Value("${ssh.user}")
    private String sshUser;
    @Value("${ssh.password}")
    private String sshPassword;
    @Value("${server.remotePort:80}")
    private Integer remotePort;
    @Value("${doc.namespace:}")
    private String namespace;
    private String healthUrl;
    private String key;
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private ReadRecordService readRecordService;
    @Autowired
    private TcpForwardService tcpForwardService;
    private final static Map<String, Function<Map<String, Object>, Boolean>> functionMap = new HashMap<>();

    @PostConstruct
    public void init() {
        healthUrl = "http://" + sshHost + ":" + remotePort + "/";
       // key = tcpForwardService.forward(sshUser, sshHost, sshPort, sshPassword, port, "localhost", remotePort);
        functionMap.put("comment_reply_create", map -> readRecordService.dealComment(map));
        functionMap.put("comment_create", map -> readRecordService.dealComment(map));
        functionMap.put("comment_reply_update", map -> readRecordService.dealComment(map));
    }


    @Scheduled(cron = "0 * * * * ?")
    public void proxyAndCheckHeath() {

        if (key != null && !check(healthUrl)) {
            tcpForwardService.restart(key);
            return;
        }
    }

    //评论hook
    public void hook(String context) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> map = objectMapper.readValue(context, new TypeReference<Map<String, Object>>() {
            });
            map = (Map<String, Object>) map.get("data");
            String actionType = map.get("action_type").toString();
            Function<Map<String, Object>, Boolean> function = functionMap.get(actionType);
            if (function != null) {
                function.apply(map);
            }
        } catch (Exception e) {
            logger.error("解析报文出错[{}] [{}]", e, context);
        }
    }

    private boolean check(String url) {
        try {
            RequestEntity<Void> build = RequestEntity.get(new URI(url)).build();
            ResponseEntity<String> exchange = restTemplate.exchange(build, String.class);
        } catch (Exception e) {
            if (e instanceof HttpClientErrorException.NotFound) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    public void publishText(String slug, String html) {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd[复习]");
        map.put("title", sdf.format(new Date()));
        map.put("slug", slug);
        map.put("format", "html");
        map.put("body", String.format("<!doctype html><div data-lake-element=\\\"root\\\" class=\\\"lake-engine lake-typography-traditional\\\" data-parser-by=\\\"lake2html\\\">%s</div>", html));
        try {
            String s = HttpSendUtil.get(String.format("/repos/%s/docs/%s", namespace, slug));
            Map<String, Object> ret = JSON.parseObject(s);
            Map<String, Object> data = (Map<String, Object>) ret.getOrDefault("data", new HashMap<>());

            if (!data.isEmpty()) {
                Integer id = (Integer) data.getOrDefault("id", 0);
                if (id != 0) {
                    try {
                        HttpSendUtil.put(String.format("/repos/%s/docs/%s", namespace, id), map);
                    } catch (HttpClientErrorException e) {
                        HttpSendUtil.delete(String.format("/repos/%s/docs/%s", namespace, id));
                        throw e;
                    }

                }
            }

        } catch (HttpClientErrorException e) {

            String s = HttpSendUtil.post(String.format("/repos/%s/docs", namespace), map);
            System.out.println(s);
        }

    }



}
